package cn.yuanqiao.web.controller.archive.wenjianzhengli;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.service.ITenantCategoryService;
import cn.yuanqiao.archive.appManager.service.ITenantMdataListService;
import cn.yuanqiao.archive.wenjianzhengli.service.IDaImportService;
import cn.yuanqiao.archive.wenjianzhengli.utils.DropDownSetFieldCellWriteHandler;
import cn.yuanqiao.archive.wenjianzhengli.utils.UploadDAO;
import cn.yuanqiao.common.constant.HttpStatus;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zjj
 * @date 2023/6/30
 */
@RestController
@RequestMapping("/archive/daImport")
public class DaImportController extends BaseController {

    @Autowired
    private IDaImportService daImportService;
    @Autowired
    private ITenantMdataListService mdataListService;
    @Autowired
    private ITenantCategoryService categoryService;

    @Log(title = "获取表头", businessType = BusinessType.IMPORT)
    @PostMapping("/getTitle")
    public AjaxResult getTitle(@RequestParam("categoryId") Long categoryId, @RequestParam("type") Integer type, MultipartFile file) {
        try {
            JSONObject object = new JSONObject();
            object.put("xlsTitle", daImportService.getTitle(categoryId, type, file).getHeadMap());  //表格表头
            TenantMdataList mdataList = new TenantMdataList();
            mdataList.setIsImport(1);
            mdataList.setType(type);
            object.put("sysTitle", mdataListService.selectTenantMdataListListByCategoryId(mdataList, categoryId));  //可导入字段
            return AjaxResult.success(object);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return AjaxResult.error();
    }

    @Log(title = "档案导入", businessType = BusinessType.IMPORT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("dataStr") String dataStr, MultipartFile file) {
        logger.info(dataStr);
        try {
            UploadDAO dao = daImportService.upload(JSONObject.parseObject(dataStr), file);
            logger.info(dao.toString());
            if (StringUtils.isNotEmpty(dao.getMsg())) {
                return  new AjaxResult(HttpStatus.ACCEPTED,dao.getMsg(),dao.getMsg().split(";"));
            } else {
                return AjaxResult.success("总计导入" + dao.getZongshu() + "条，耗时:" + longTileString(dao.getTime()));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    private String longTileString(long time) {
        if (time < 1000L) {
            return time + "毫秒";
        } else if (time <= 60000L) {
            return (time / 1000L) + "秒";
        } else {
            return (time / (60L * 1000L)) + "分钟";
        }
    }

    @Log(title = "模板下载", businessType = BusinessType.EXPORT)
    @PostMapping("/download")
    public void download(@RequestParam("categoryId") Long categoryId, @RequestParam("type") Integer type, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        TenantCategory category = categoryService.selectTenanCategoryByID(categoryId);
        String typeName = "";
        if (type == 3) {
            typeName = "(项目层)";
        } else if (type == 1) {
            typeName = "(卷层)";
        } else if (type == 0) {
            typeName = "(件层)";
        } else if (type == 6) {
            typeName = "(项目下卷层)";
            type = 1;
        }
        String fileName = URLEncoder.encode(category.getName() + typeName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        Map<Integer, Object> data = mdataListService.getIsExport(category.getGroupId(), type);
        List<List<String>> headList = (List<List<String>>) data.get(0);  //表头
        Map<Integer, String[]> mapList = (Map<Integer, String[]>) data.get(1);  //字典
        if ("(项目下卷层)".equals(typeName)) {
            List<String> titile = new ArrayList<>();
            titile.add("项目编号(关联)");
            headList.add(titile);
        }
        EasyExcel.write(response.getOutputStream()).head(headList).registerWriteHandler(new DropDownSetFieldCellWriteHandler(mapList)).sheet(typeName).doWrite(new ArrayList<>());
    }

    /**
     *
     * @param id 门类ID
     * @param type v=卷 f=件 x=项目
     * @param file
     * @return
     */
    @PostMapping("/uploadXml/{id}/{type}")
    public AjaxResult uploadXml(@PathVariable("id") Long id,@PathVariable("type") String type,MultipartFile file){
        String msg = daImportService.uploadXml(id,type,file);
        return AjaxResult.success(msg);
    }

    /**
     *
     * @param id 门类ID
     * @param type v=卷 f=件 x=项目
     * @param file
     * @return
     */
    @PostMapping("/uploadTxt/{id}/{type}")
    public AjaxResult uploadTxt(@PathVariable("id") Long id,@PathVariable("type") String type,MultipartFile file){
        String msg = daImportService.uploadTxt(id,type,file,"txt");
        return AjaxResult.success(msg);
    }

    /**
     *
     * @param id 门类ID
     * @param type v=卷 f=件 x=项目
     * @param file
     * @param name 数据库文件用户名 archive
     * @param pwd 数据库文件密码 archive
     * @return
     */
    @PostMapping("/uploadMdb/{id}/{type}")
    public AjaxResult uploadMdb(@PathVariable("id") Long id,@PathVariable("type") String type,MultipartFile file,@RequestParam(value = "name") String name,@RequestParam(value = "pwd") String pwd){
        if("archive".equals(name) && "archive".equals(pwd)){
            String msg = daImportService.uploadTxt(id,type,file,"mdb");
            return AjaxResult.success(msg);
        }else {
            return AjaxResult.error("用户名或密码错误!");
        }

    }

}
